<?php

if(!defined('URL_KEINOS_FUNCTIONS'))  { die('<p>Constans \'URL_KEINOS_FUNCTIONS\' must be set to call the KEINOS functions.</p>'); }
if(!defined('PATH_KEINOS_FUNCTIONS')) { die('<p>Constans \'PATH_KEINOS_FUNCTIONS\' must be set to call the KEINOS functions.</p>'); }

/**
 * ================================================
 *  各種ファイル名の変数
 * ================================================
 */
$sName_File_KEINOS_FUNCTIONS_all = "KEINOS_functions.inc";
$sName_File_system_info          = "system_info.dat";
$sName_File_KEINOS_css_reset     = "default.KEINOS_css-reset.css";
$sName_File_KEINOS_setup         = basename($_SERVER['SCRIPT_NAME']);
$sName_File_sample_initialize    = "sample.initialize.inc";

/**
 * ================================================
 *  HTMLヘッダー出力
 * ================================================
 */
$sURL_KEINOS_css_reset = URL_KEINOS_FUNCTIONS . $sName_File_KEINOS_css_reset;
echo '<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Moctezuma - KEINOS INSTALLER</title>';
echo '<link rel="stylesheet" type="text/css" href="' . $sURL_KEINOS_css_reset .'" charset="utf-8" />';
echo '</head><body style="text-align:left;">';
echo "<h1>KEINOS Installer</h1>";

/**
 * ================================================
 *  セーフモードの確認
 * ================================================
 *  セーフモードの場合、ディレクトリが作成できないため。
 */
if(ini_get("safe_mode")){
    $sMsg  = "<h1>Error:PHPがセーフモードで動作しています</h1>";
    $sMsg .= "<p>セーフモードではディレクトリが作成できません。{$sName_File_KEINOS_setup}をCGIモードで動かしてください。</p>";
    $sMsg .= "<p><a href='http://www.google.co.jp/search?hl=ja&q=%E3%82%BB%E3%83%BC%E3%83%95%E3%83%A2%E3%83%BC%E3%83%89%E3%81%AB%E3%82%88%E3%82%8B%E5%88%B6%E9%99%90%E3%81%A8%E5%AF%BE%E5%87%A6%E6%96%B9%E6%B3%95&btnG=Google+%E6%A4%9C%E7%B4%A2&lr=&aq=f&oq='>PHPをCGIモードで動かす方法</a></p>";
    die($sMsg);
}

/**
 * ================================================
 *  インストールオプションの画面表示
 * ================================================
 */
$sInstallToken   = md5(session_id() . $_SERVER['REMOTE_ADDR'] .$_SERVER['SERVER_ADDR']);
$sURL_ThisScript = htmlspecialchars($_SERVER["SCRIPT_NAME"]);

// フォームの出力
?>
<form method="POST" action="<?=$sURL_ThisScript; ?>">
    <h2>インストールオプション</h2>
    <input type="hidden" name="t" value="<?=$sInstallToken;?>" />
    <input type="checkbox" name="force_PEAR" value="yes" />PEARを強制インストールする<br>
    <input type="checkbox" name="reinstall" value="yes" />再インストールする<br>
    <input type="submit" value="更新／アップデート／再インストール" />
</form>
<hr>
<? //フォームここまで

/**
 * ================================================
 *  インストール・オプションのチェック
 * ================================================
 */
$bAuth         = ($_POST['t']==$sInstallToken) ? TRUE   : FALSE;
$bInstall_PEAR = ($_POST['force_PEAR'])        ? $bAuth : FALSE;
$bInstall_RE   = ($_POST['reinstall'])         ? $bAuth : FALSE;

/**
 * ================================================
 *  versionの確認
 * ================================================
 */
$sPath_system_info = PATH_KEINOS_FUNCTIONS . $sName_File_system_info;

if( File_Exists($sPath_system_info)){
    $aSystemInfo = unserialize(file_get_contents($sPath_system_info));
    $sCurrentSystemVersion = ( md5_file(URL_KEINOS_FUNCTIONS) );
    $sCurrentSetupVersion  = ( md5_file(URL_KEINOS_SETUP) );

    if( $sCurrentSetupVersion<>(md5_file($_SERVER['SCRIPT_FILENAME'])) ){
        $sSetupURL = URL_KEINOS_SETUP;
        $sMsg = <<<ID
            <h2>セットアップのスクリプトがバージョンアップされています。</h2>
            <p>{$sName_File_KEINOS_setup}を下記URLよりダウンロードして上書きしてください。</p>
            <p><b><a href="{$sSetupURL}" target="_blank">{$sSetupURL}</a></b></p>
            <hr>
ID;
        echo $sMsg;
    }

    if( ($aSystemInfo['version_system']==$sCurrentSystemVersion) && !($bInstall_RE) ){
        //デバッグ用
        if(FALSE){
            echo "<hr><pre>";
            print_r($aSystemInfo);
            echo "</pre>";
        }

        $sMsg = <<<ID
            <h2>システムのバージョンの変更はありませんでした</h2>
            <p>再インストールをしたい場合は、上記インストールオプションにチェックを入れ、再実行してください。</p>
ID;
        echo $sMsg;

        echo "<hr><h2>インストール情報</h2>";
        echo "<table>";
        echo "<tr><th>ファイル名</th><th>インストール状況</th><th>'{$sName_File_KEINOS_FUNCTIONS_all}' に追加</th></tr>\r\n";
        foreach($aSystemInfo['function_list'] as $sKey => $aItem){
            if(!Empty($aItem['filename'])){
                $sPath_File = realpath(PATH_KEINOS_FUNCTIONS . $aItem['filename']);
                $sDownloadStatus = file_exists( $sPath_File ) ? "<font color=blue>済み</font>" : "<font color=green>未導入</font>";
                $sIsStatic = ($aItem['is_static']) ? "<font color=blue>済み</font>" : "<font color=green>未導入(使用時要include)</font>";
                $sURL_TargetFile = URL_KEINOS_FUNCTIONS . $aItem['filename'];
                echo "<tr><td><a href='{$sURL_TargetFile}' target='_view_source'>{$aItem['filename']}</a></td><td>{$sDownloadStatus}</td><td>{$sIsStatic}</td></tr>";
            }
        }
        echo "</table>";

        echo "<hr>";
        echo "<h2>環境情報 ({$sName_File_system_info})</h2>";
        echo "<table>\r\n";
        echo "<tr><th>KEY</th><th>VALUE</th></tr>\r\n";
        foreach($aSystemInfo as $sKey => $sValue){
            if(!Empty($sValue) && !Is_Array($sValue)){
                echo "<tr><td>{$sKey}</td><td><span style='white-space:nowrap'>{$sValue}</span></td></tr>\r\n";
            }
        }
        echo "</table>\r\n";
        echo "<hr>";
        echo "<p>以上</p>";
        die();

    }
    
    if($bInstall_RE) echo "<h2 style='color:red'>システムの再インストールを実行</h2>";
}

if(!isset($aSystemInfo)) $aSystemInfo = array();


/**
 * ================================================
 *  ユーザー関数の読み込み
 * ================================================
 */

$aKEINOS_function_List[] = array(
        'filename' => "function.fprint_r.inc",
        'is_static' => TRUE,
    );
$aKEINOS_function_List[] = array(
        'filename' => "function.loaddata.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.savedata.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.deletedata.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.listdata.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.listdir.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.dir_exists.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.fgetcsv_reg.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.get_spreadsheet.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.fresizeimage.inc",
        'is_static' => FALSE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.ffindext.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.fescape.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.getdirsize.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.chmod_all.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.utf_8.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.checkEncoding.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.sjis.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.fconvert_izon_char.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.keinos_mail.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.fIsMobile.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.scandir.php5.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.file_post_contents.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.file_put_contents.php5.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.str_getcsv.php5.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.fWatermark.ASIDO.inc",
        'is_static' => FALSE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.check_smarty.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.check_pear.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.make_basic_crypt.inc",
        'is_static' => FALSE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.get_microtime.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.ssl_create_pairkey.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.ssl_encrypt.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.ssl_decrypt.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.short_url.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.is_ie6.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.fIsIphone.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.shorten_url.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "function.file_get_googletext.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "",
        'is_static' => TRUE,
    );


/**
 * ================================================
 *  Classの読み込み
 * ================================================
 */
$aKEINOS_function_List[] = array(
        'filename' => "class.ccolor.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "class.chttp_request.HTTP_REQUEST.inc",
        'is_static' => FALSE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "class.cdocument.inc",
        'is_static' => FALSE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "class.cdata.inc",
        'is_static' => TRUE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "class.cyui_css.inc",
        'is_static' => FALSE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "class.camazonapi.inc",
        'is_static' => FALSE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "class.MailMan.inc",
        'is_static' => FALSE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "class.cKuler.inc",
        'is_static' => FALSE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "class.cHatenaApi.inc",
        'is_static' => FALSE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "",
        'is_static' => FALSE,
    );

/**
 * ================================================
 *  その他のファイルの読み込み
 * ================================================
 */
//環境変数
$sName_File_system_environment = "system_environment.inc";
$aKEINOS_function_List[] = array(
        'filename' => $sName_File_system_environment,
        'is_static' => FALSE,
    );

//.htaccessのデフォルト
$aKEINOS_function_List[] = array(
        'filename' => "default.htaccess",
        'is_static' => FALSE,
    );
//initialize.incのデフォルト
$sName_File_default_initialize = "default.initialize.inc";
$aKEINOS_function_List[] = array(
        'filename' => $sName_File_default_initialize,
        'is_static' => FALSE,
    );

//動作のサンプルファイル
$aKEINOS_function_List[] = array(
        'filename' => "sample.sample.php",
        'is_static' => FALSE,
    );
//YUI CSS 2.7.0
$aKEINOS_function_List[] = array(
        'filename' => "default.KEINOS_css-reset.css",
        'is_static' => FALSE,
    );

//jQuery 1.3.2
$aKEINOS_function_List[] = array(
        'filename' => "default.javascript.jquery.js",
        'is_static' => FALSE,
    );

$aKEINOS_function_List[] = array(
        'filename' => "",
        'is_static' => FALSE,
    );


/**
 * ================================================
 *  テンポラリユーザ関数
 * ================================================
 */

function fTrimPHPtag($s){
    $s = trim($s);
    $s = preg_replace('/^<\?php/','',$s,1);
    $s = preg_replace('/\?>$/','',$s,1);
    return $s;
}


/**
 * ================================================
 *  ファイルのダウンロード処理
 * ================================================
 */

echo "<h2>更新情報</h2>\r\n";
echo "<table>";
echo "<tr><th>FILE NAME</th><th>DOWNLOAD STATUS</th><th>ADD TO '{$sName_File_KEINOS_FUNCTIONS_all}'</th></tr>\r\n";
foreach($aKEINOS_function_List as $key=>$value){
    if(!Empty($value['filename'])){
        //スクリプトのダウンロード
        $sTemp_URL = URL_KEINOS_FUNCTIONS . $value['filename'];
        $sContent = file_get_contents($sTemp_URL);

        //Google Codeがレスポンスが悪い時の処理
        if(Empty($sContent)){
            sleep(5);
            $sContent = file_get_contents($sTemp_URL);
            if(Empty($sContent)) die("DOWNLOAD ERROR:<a href='{$sTemp_URL}'>{$sTemp_URL}</a>");
        }
        
        $sVerifyKey    = md5($value['filename']);
        $sVerifyValue  = md5($sContent);
        $aFunction_version_List[$sVerifyKey] = $sVerifyValue;
        $bHasChange = ($aSystemInfo['function_version'][$sVerifyKey] == $sVerifyValue) ? FALSE : TRUE;

        echo "<tr>";
        $sURL_TargetFile = URL_KEINOS_FUNCTIONS . $value['filename'];
        echo "<td><a href='{$sURL_TargetFile}' target='_view_source' charset='utf-8'>{$value['filename']}</a></td>"; //FILE NAME

        if($bHasChange || $bInstall_RE){
            $sPath_installer = PATH_KEINOS_FUNCTIONS . $value['filename'];
            $bFileExists = file_exists($sPath_installer) ? TRUE : FALSE;
            $bResult = file_put_contents($sPath_installer,$sContent);
            echo ($bResult) ? ($bFileExists) ? "<td><b><font color=blue>UPDATE!</font></b></td>" : "<td><b><font color=blue>OK</font></b></td>" : "<td><b><font color=red>NG<br>SAVE ERROR</font></b></td>"; //DOWNLOAD
        }
        else{
            echo "<td><font color=green>OMITTED</font> (No change)</td>";
        }
        if($value['is_static']){
            //Static Fileに追加
            $sStaticContent_for_KEINOS_FUNCTIONS .= fTrimPHPtag($sContent);
            echo "<td><font color=blue>YES</font></td>";
        }
        else{
            echo "<td><font color=green>NO</font> (OMIT)</td>";
        }
        echo "</tr>";
        $aLogDownloadedFunctions[md5($value['filename'])] = md5($sVerify);
    }
}
echo "</table>";

echo "<pre style='text-align:left;font-family:monospace; white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;white-space: pre-wrap;word-wrap: break-word;'>";

/**
 * Static Fileの作成
 * よく使う関数を１ファイル（KEINOS_functions.inc）にまとめてアクセス負荷を抑える
 *
 */
$sStaticContent_for_KEINOS_FUNCTIONS = "<" . "?php\r\n\r\n" . $sStaticContent_for_KEINOS_FUNCTIONS . "\r\n\r\n?" . ">";
$sPath_KEINOS_FUNCTIONS_all = PATH_KEINOS_FUNCTIONS . $sName_File_KEINOS_FUNCTIONS_all;
$bResult                    = @file_put_contents($sPath_KEINOS_FUNCTIONS_all,$sStaticContent_for_KEINOS_FUNCTIONS);
echo "<p>■{$sName_File_KEINOS_FUNCTIONS_all}の作成：";
echo ($bResult) ? "<font color=blue>OK</font>" : "<b><font color=red>NG</font></b>";
echo "</p>";

/**
 * ================================================
 *  .htaccessの作成と保存
 * ================================================
 */
$sHtaccess = File_Exists("./KEINOS/default.htaccess") ? File_Get_Contents("./KEINOS/default.htaccess") : "";
$bHtaccess = File_Put_Contents("./KEINOS/.htaccess",$sHtaccess);

/**
 * ================================================
 *  システム環境情報の保存
 * ================================================
 */

$aSystemInfo = File_Exists($aSystemInfo) ? unserialize(file_get_contents($aSystemInfo)) : array();
$sPath_root  = str_replace(basename($_SERVER['SCRIPT_NAME']),"",realpath(basename($_SERVER['SCRIPT_NAME'])));

$aSystemInfo['dir_system']   = "KEINOS";
$aSystemInfo['dir_data']     = "_data";
$aSystemInfo['dir_template'] = "_template";
$aSystemInfo['dir_cache']    = "_cache";
$aSystemInfo['dir_compile']  = "_compile";

$sPath_Install_dir = $sPath_root . $aSystemInfo['dir_system'] . DIRECTORY_SEPARATOR;

$aSystemInfo['path_lib']      = $sPath_root; if(!defined('PATH_ROOT_LIB')) { define('PATH_ROOT_LIB', $sPath_root);}
$aSystemInfo['path_system']   = $sPath_Install_dir;
$aSystemInfo['path_data']     = $sPath_Install_dir . $aSystemInfo['dir_data']     . DIRECTORY_SEPARATOR;
$aSystemInfo['path_template'] = $sPath_Install_dir . $aSystemInfo['dir_template'] . DIRECTORY_SEPARATOR;
$aSystemInfo['path_cache']    = $sPath_Install_dir . $aSystemInfo['dir_cache']    . DIRECTORY_SEPARATOR;
$aSystemInfo['path_compile']  = $sPath_Install_dir . $aSystemInfo['dir_compile']  . DIRECTORY_SEPARATOR;

$aSystemInfo['path_setup_file']  = realpath(basename($_SERVER['SCRIPT_NAME']));
$aSystemInfo['path_system_info'] = $sPath_system_info;

$aSystemInfo['bIsWindows'] = (substr(PHP_OS, 0, 3) == 'WIN') ? TRUE : FALSE; //Windowsサーバ上で稼動しているか

$aSystemInfo['version_setup']             = ( md5_file(realpath(basename($_SERVER['SCRIPT_NAME']))) );
$aSystemInfo['version_system']            = ( md5_file(URL_KEINOS_FUNCTIONS) );
$aSystemInfo['function_list']             = $aKEINOS_function_List;
$aSystemInfo['function_version']          = $aFunction_version_List;
$aSystemInfo['path_static_load_function'] = $sPath_KEINOS_FUNCTIONS_all;

if(!(File_Put_Contents($sPath_system_info,serialize($aSystemInfo)))){
    die("インストールログの作成に失敗しました。");
}

/**
 * ==================================
 *  その他環境導入
 * ==================================
 */

include_once($sPath_KEINOS_FUNCTIONS_all);

/**
 * ---------------------------------
 *  Smartyのインストールチェック
 * ---------------------------------
 */
include_once("./KEINOS/function.check_smarty.inc");
echo "<p>■Smartyのインストール：";
echo (check_smarty()) ? "<font color=green>インストール済み</font>" : "<b><font color=red>NG</font></b>";
echo "</p>";

/**
 * ---------------------------------
 *  PEARのインストールチェック
 * ---------------------------------
 */
include_once("./KEINOS/function.check_pear.inc");
$bIs_PEAR_installed = check_pear();

echo "<p>■PEARのインストール：";
echo ($bIs_PEAR_installed) ? "<font color=green>インストール済み</font>" : "<b><font color=red>NG</font></b>";
echo "</p>";

if(!($bIs_PEAR_installed) || $bInstall_PEAR){
    $sTemp_Dir = "./KEINOS/PEAR";
    $sPath_gopear = $sTemp_Dir . "/go-pear.php";
    $bResult_mkdir = @mkDir($sTemp_Dir,0777);
    if($bResult_mkdir){
        chmod($sTemp_Dir,0777);
        chown($sTemp_Dir,"keinos");
        $sURL_pear_package_manager = "http://pear.php.net/go-pear";
        $bResult_pear = file_put_contents($sPath_gopear,file_get_contents($sURL_pear_package_manager));
    }
    echo "<p style='margin-left:15px;'>PEARのインストールディレクトリ作成：";
    echo ($bResult_mkdir) ? "<b><font color=blue>OK</font></b>" : "<b><font color=red>NG</font></b>";
    if(!$bResult_mkdir && dir_exists($sTemp_Dir)) echo "<br>PEARディレクトリはすでにあります。";
    echo "</p>";
    echo "<p style='margin-left:15px;'>go-pear.phpファイルのインストール：";
    echo ($bResult_pear) ? "<font color=blue>OK</font> [<a href='./KEINOS/PEAR/go-pear.php'>PEARパッケージマネージャーのインストール</a>]※特にディレクトリの変更なしでインストールしてください。" : "<b><font color=red>NG</font></b>";
    if(!$bResult_pear && file_exists($sPath_gopear)) echo "<br>go-pear.phpはすでにあります。";
    echo "</p>";
    if($bResult_pear){
        $bIs_custom_PEAR = TRUE;
        $sIncludePath_PEAR  = PATH_KEINOS_FUNCTIONS . DIRECTORY_SEPARATOR . "PEAR" . DIRECTORY_SEPARATOR . "PEAR". DIRECTORY_SEPARATOR;
    }
}


/**
 * ---------------------------------
 *  ディレクトリの作成
 * ---------------------------------
 */

//環境変数の読み込み
require_once("./KEINOS/{$sName_File_system_environment}");

//データ・ディレクトリの作成
$sTemp_Dir = $aRealPath['data_dir'];
$bResult_mkdir = @mkDir($sTemp_Dir, 0777);
echo "<p>■データ・ディレクトリの作成：";
echo ($bResult_mkdir) ? "<font color=blue>OK</font>" : "<b><font color=red>NG</font></b>";
if(!$bResult_mkdir && dir_exists($sTemp_Dir)) echo "　　'{$sTemp_Dir}'ディレクトリはすでにあります。";
echo "</p>";

//テンプレート・ディレクトリの作成
$sTemp_Dir = $aRealPath['template_dir'];
$bResult_mkdir = @mkDir($sTemp_Dir, 0777);
echo "<p>■テンプレート・ディレクトリの作成：";
echo ($bResult_mkdir) ? "<font color=blue>OK</font>" : "<b><font color=red>NG</font></b>";
if(!$bResult_mkdir && dir_exists($sTemp_Dir)) echo "　　'{$sTemp_Dir}'ディレクトリはすでにあります。";
echo "</p>";

//サンプル・テンプレートの作成
$sSampleTemplate = "<h1>テンプレートの動作サンプル</h1>\r\n<p>Given Time :<{" . '$' . "data.sample|date_format:\"%Y年%m月%d日 %H時%M分%S秒\"}>\r\n";
$bResult = file_put_contents($aRealPath['template_dir']. "sample.tpl",$sSampleTemplate);
echo "<p style='margin-left:15px;'>サンプル・テンプレートファイルの作成：";
echo ($bResult) ? "<font color=blue>OK</font>" : "<b><font color=red>NG</font></b>";
echo "</p>";

//コンパイル・ディレクトリの作成
$sTemp_Dir = $aRealPath['compile_dir'];
$bResult_mkdir = @mkDir($sTemp_Dir, 0777);
echo "<p>■コンパイル・ディレクトリの作成：";
echo ($bResult_mkdir) ? "<font color=blue>OK</font>" : "<b><font color=red>NG</font></b>";
if(!$bResult_mkdir && dir_exists($sTemp_Dir)) echo "　　'{$sTemp_Dir}'ディレクトリはすでにあります。";
echo "</p>";

//キャッシュ・ディレクトリの作成
$sTemp_Dir = $aRealPath['cache_dir'];
$bResult_mkdir = @mkDir($sTemp_Dir, 0777);
echo "<p>■キャッシュ・ディレクトリの作成：";
echo ($bResult_mkdir) ? "<font color=blue>OK</font>" : "<b><font color=red>NG</font></b>";
if(!$bResult_mkdir && dir_exists($sTemp_Dir)) {
    echo "　　'{$sTemp_Dir}'ディレクトリはすでにあります。";
    session_save_path($aSystemInfo['path_cache']);
    session_start();
}
echo "</p>";


/**
 * --------------------------
 *  initialize.incの作成
 * --------------------------
 */

$aKEINOS_ENVIRONMENT['bIs_custom_PEAR']   = $bIs_custom_PEAR;
$aKEINOS_ENVIRONMENT['include_path_PEAR'] = $sIncludePath_PEAR;

$sKEINOS_ENVIRONMENT = addslashes(serialize($aKEINOS_ENVIRONMENT));
$sRealPath           = addslashes(serialize($aRealPath));

$sInitialize  = "";
$sInitialize .= "ini_set('display_errors', 'On');\r\n";
$sInitialize .= '$' . "aKEINOS_ENVIRONMENT = unserialize(" . "\"{$sKEINOS_ENVIRONMENT}\");\r\n";
$sInitialize .= '$' . "aRealPath = unserialize("           . "\"{$sRealPath}\");\r\n";

//環境変数との合成
$sInitialize  = '<' . '?php' ."\r\n{$sInitialize}\r\n?" . '>' . "\r\n";

//KEINOS_functions.incとの合成
$sInitialize .= file_get_contents("./KEINOS/{$sName_File_KEINOS_FUNCTIONS_all}") . "\r\n";

//デフォルトとの合成
$sInitialize .= file_get_contents("./KEINOS/{$sName_File_default_initialize}") . "\r\n";


//initialize.incの保存
$sTemp_Path = "./KEINOS/initialize.inc";
$bResult = file_put_contents($sTemp_Path,$sInitialize);
echo "<p>■initialize.incの作成：";
echo ($bResult) ? "<font color=blue>OK</font>" : "<b><font color=red>NG</font></b>";
echo "</p>";

if(file_exists($sTemp_Path)){
    $sPathToIncludeInitialize = PATH_KEINOS_FUNCTIONS . "initialize.inc";
    $sSampleInitialize  = "include_once('{$sPathToIncludeInitialize}');\r\n";
    $sSampleInitialize  = '<' . '?php' ."\r\n{$sSampleInitialize}?" . '>';
//    $sTemp_Path = "./KEINOS/{$sName_File_sample_initialize}";
    $bResult = @file_put_contents("./KEINOS/{$sName_File_sample_initialize}",$sSampleInitialize);
    $sTemp_Path = realpath("./KEINOS/{$sName_File_sample_initialize}");
    $sMsg =<<<ID
    <font color=red>重要</font></b><p style='padding:5px;border:solid 2px red; font-weight:bold;margin-left:15px;'>"initialize.inc"をinclude_onceするディレクトリに、{$sTemp_Path}のファイルをコピーして、"initialize.inc"にリネームしてください。<br>.htaccessでinclude_pathを指定できないサーバ対策です。</p>
ID;
    echo $sMsg;
}
else{
    echo "file not found:{$sTemp_Path}";
}

echo "</pre>";

echo "<p>DONE</p>";

?>